<template>
  <div>
    <el-col :span="24" class="bg1">
      <div class="grid-content bg-purple">
        <FormPanel ref="formPanel" :list="formList" :cols="3" :labelWidth="110" :isSubmitBtn="false" @formChange="changeHandle" />
      </div>
    </el-col>
    <el-col :span="24" class="bg2">
      <BreakSpace label="VIN列表" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
      <!-- :fetchapi="fetchApi"
        :params="fetchParams"-->
      <FilterTable
        ref="table"
        :onSyncTableData="vinTableChangeFun"
        selectionType="single"
        :isSelectColumn="false"
        :isMemoryPagination="isAdd"
        height="200"
        :columns="columns"
        :fetchapi="fetchapiVin"
        :params="fetchParamsVin"
        :dataSource="dataSource"
        datakey="records"
        columnsRef="yxqPjxmTable"
        :isColumnFilter="true"
        :onColumnsChange="columns => (this.columns = columns)"
        :onRowSelectChange="arr => (this.onChangeColumn = arr)"
      >
        <template slot="controls" >
          <el-button size="small" type="primary" icon="el-icon-plus" @click="addVpn">添加VIN</el-button>
          <!--<el-button size="small" type="primary" icon="el-icon-import" @click="importHandle">VIN导入</el-button>-->
          <el-button size="small" type="primary" icon="el-icon-download" @click="downHandle">VIN模板下载</el-button>

          <UploadFile style="margin: 0 10px;" isOnlyButton :limit="20" type="primary" :fileTypes="['xls', 'xlsx']" icon="el-icon-upload" :actionUrl="actionUrl" @change="successHandler"
            >VIN导入
          </UploadFile>
        </template>
      </FilterTable>
    </el-col>

    <!-- <el-col :span="24" class="bg2">
      <BreakSpace label="活动项目列表" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
      <FilterTable
        ref="tableSport"
        selectionType="single"
        height="200"
        :isSelectColumn="false"
        :columns="columnSport"
        :onSyncTableData="sportTableChangeFun"
        :isMemoryPagination="true"
        columnsRef="yxqSportTable"
        :onColumnsChange="columns => (this.columnSport = columns)"
        :onRowSelectChange="arr => (this.onChangeColumn = arr)"
      >
        <template slot="controls" slot-scope="props">
          <el-button size="small" type="primary" icon="el-icon-plus" :disabled="disableState || addBtnDisabled" @click="addSport">添加活动项目</el-button>
        </template>
      </FilterTable>
    </el-col>

    <el-col :span="24" class="bg2">
      <BreakSpace label="配件列表" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>

      <FilterTable
        ref="tablePeij"
        height="200"
        :onSyncTableData="peijTableChangeFun"
        :onCellChange="onCellChange"
        :isSelectColumn="false"
        selectionType="single"
        :columns="columnPeij"
        :isMemoryPagination="true"
        columnsRef="yxqPeijTable"
        :onColumnsChange="columns => (this.columnPeij = columns)"
        :onRowSelectChange="arr => (this.onChangeColumn = arr)"
      >
        <template slot="controls" slot-scope="props">
          <el-button size="small" type="primary" icon="el-icon-plus" :disabled="disableState || addBtnDisabled" @click="addPeij">添加配件</el-button>
        </template>
      </FilterTable>
    </el-col>

    <el-col :span="24" class="bg2" v-if="handleType == 'edit'">
      <BreakSpace label="索赔审核信息" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
      <FilterTable
        ref="tableSuopei"
        height="200"
        :isSelectColumn="false"
        selectionType="single"
        :columns="columnSuopei"
        :isMemoryPagination="true"
        columnsRef="yxqSuopeiTable"
        :onColumnsChange="columns => (this.columnSuopei = columns)"
        :onRowSelectChange="arr => (this.onChangeColumn = arr)"
      >
      </FilterTable>
    </el-col> -->

    <div class="dialogBottmView">
      <multiuse-button type="primary" class="btnStyle" :click="closeMenu.bind(this, 1)">保存</multiuse-button>

      <!-- <multiuse-button v-if="handleType == 'edit'" :disabled="!isClicked" type="primary" class="btnStyle" :click="closeMenu.bind(this, 2)">下发 </multiuse-button> -->

      <multiuse-button type="primary" class="btnStyle" :click="closeMenu.bind(this, 3)">关闭</multiuse-button>
    </div>
    <BaseDialog :visible.sync="visibleVin" title="VIN查询" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" destroyOnClose>
      <add-vin @selectArr="selectFun" @closeVin="closeDialog"></add-vin>
    </BaseDialog>

    <BaseDialog :visible.sync="visibleSport" title="维修项目选择" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" destroyOnClose>
      <add-sport @selectArr="selectSportFun" @closeVin="closeDialog"></add-sport>
    </BaseDialog>

    <BaseDialog :visible.sync="visiblePeij" title="配件选择" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" destroyOnClose>
      <add-peij :status="status" @selectArr="selectPeijFun" @closeVin="closeDialog" :powerType="powerType"></add-peij>
    </BaseDialog>

    <BaseDialog :visible.sync="visibleDelear" title="选择经销商" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" destroyOnClose>
      <add-delear :vin="selectObj['vin']" @selectArr="selectDelearFun" @closeDelear="closeDialog"></add-delear>
    </BaseDialog>
  </div>
</template>

<script>
import { deleteTtRpMaVin, getByMaId, delMaItem, downVinTemDelete, getVinByMaId, saveDown, getAllUser, queryUnitCode, byAllTranslate } from '@/api/repair/batchEventManagement/activityDistribution';
import { dictionary } from '@/utils/dictMixin';
import addVin from '@/pages/repair/batchEventManagement/activityDistribution/addVin.vue';
import addDelear from '@/pages/repair/batchEventManagement/activityDistribution/addDelear';
import { isEmpty } from '@/utils/utils';
import _ from 'lodash';
import { exportExcelFile } from '@/utils/index';
import { arrayObjDeWeight } from '@/utils';
import { dealerMixin } from '@/pages/repair/batchEventManagement/dealerMixin';
import moment from 'moment';
import { getAppId } from '@/assets/js/auth';

export default {
  name: 'add',
  mixins: [dictionary, dealerMixin],
  /*handleType add 新增  edit  编辑*/
  props: ['handleType', 'data', 'row'],
  data() {
    this.saveData = null;
    return {
      columnSport: this.createTableColumnSport(),
      columnPeij: this.createTableColumnPeij(),
      columnSuopei: this.createTableColumnSuopei(),
      columns: this.createTableColumns(),
      formList: this.createFormList(),
      visibleVin: false,
      visibleSport: false,
      visiblePeij: false,
      visibleDelear: false,
      visibleMainCode: false,
      isAdd: this.handleType == 'add',
      fetchParams: { xhrAbort: true },
      fetchParamPeij: { xhrAbort: true },
      fetchParamSport: { xhrAbort: true },
      fetchParamSuopei: { xhrAbort: true },
      dataSource: [],
      fetchApiPeij: '',
      fetchApi: '',
      fetchApiSport: '',
      fetchApiSuopei: '',
      fetchapiVin: getVinByMaId,
      fetchParamsVin: { xhrAbort: true },
      onChangeColumn: [],

      /*活动删除列表数组*/
      delSportArr: [],
      /*配件删除列表数据*/
      delPartArr: [],
      /*vin删除列表数组*/
      delVinArr: [],

      vinArr: [] /**/,
      sportArr: [],
      peijArr: [],
      status: 1 /*1  表单选择  2 新建配件*/,
      detailObj: {},
      UploadFileIsShow: false,
      /*是否可下发*/
      isClicked: false,
      /*vin对象 选择*/
      selectObj: {},

      actionUrl: '/api/dmscloud.activity/ttRpMa/uploadVinTem'
    };
  },
  computed: {
    disableState() {
      return true;
    },
    // 质量部下发数据不允许新增
    addBtnDisabled() {
      return true;
    },
    powerType() {
      return this.handleType == 'add' ? 50001002 : 50001001;
    }
  },
  components: {
    addVin,
    addDelear
  },
  mounted() {
    // console.log('maId---', this.maId);

    this.BaseTable = this.$refs.table.$refs.pageTable;
    // this.BaseSportTable = this.$refs.tableSport.$refs.pageTable;
    // this.BasePeijTable = this.$refs.tablePeij.$refs.pageTable;

    this.getAllDelears(this.columns, ['salesDealer', 'resDealer'], 'table');

    if (this.handleType == 'edit') {
      this.BaseSuopeiTable = this.$refs.tableSuopei.$refs.pageTable;
      this.getData();
      // 处理是否索赔通过审核
      // if (this.row.ifClaim == 10041001) {
      //   this.handleClaim();
      //   this.columnPeij.find(x => x.dataIndex == 'counts').editRequired = false;
      //   this.columnPeij.find(x => x.dataIndex == 'counts').editable = false;
      // }
    }
    this.getUnit();

    this.initSelect();
    this.initData();
    // this.initDelear();
  },
  methods: {
    handleClaim() {
      // 禁用所有的编辑项，只可以下发和关闭
      this.formList.forEach(x => {
        x.disabled = true;
        x.rules = [];
        x.placeholder = '';
      });
    },
    async getUnit() {
      this.getAllUnitCode(this.columnPeij, ['unit'], 'table');

      // const res = await queryUnitCode();
      // this.columns.find(item => item.dataIndex === 'salesDealer').dictItems = res.data.map(x => ({
      //   text: x.UNIT_NAME,
      //   value: x.UNIT_CODE
      // }));
    },

    /*配置数量发生改变的时候执行*/
    onCellChange(e, obj) {
      let counts = isEmpty(obj['counts']) ? '0' : obj['counts'];
      let price = isEmpty(obj['price']) ? '0' : obj['price'];
      let amount = obj['amount'];

      let toatalCount = counts * price ? counts * price : 0;
      if (obj['partFrom'] == 10251002) {
        obj['amount'] = 0.0;
      } else {
        obj['amount'] = toatalCount.toFixed(2);
      }

      // this.BasePeijTable.DO_REFRESH(false);

      // this.columnPeij.find((item,index)=>item.dataIndex=='amount').initialValue=1//toatalCount
    },

    async initSelect() {
      // let res = await getAllUser();
      // // 去重
      // let dataList = arrayObjDeWeight(res.data, 'userId');
      //
      // this.columnSuopei.find(item => item.dataIndex === 'createdBy').dictItems = dataList.map(x => ({
      //   text: x.employeeName,
      //   value: x.userId
      // }));

      this.getAllUsers(this.columnSuopei, ['createdBy'], 'table');
    },

    async initDelear() {
      let res = await byAllTranslate();
      let dataList = arrayObjDeWeight(res.data, 'userId');
      this.columnSuopei.find(item => item.dataIndex === 'createdBy').dictItems = dataList.map(x => ({
        text: x.dealerName,
        value: x.dealerCode
      }));
    },

    /*导入*/
    importHandle() {
      this.handleType = 'import';
      this.UploadFileIsShow = true;
    },
    /*下载模板*/
    downHandle() {
      this.handleType = 'down';
      this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
        confirmButtonText: '下载',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          downVinTemDelete()
            .then(res => {
              console.log(res, 'res');
              exportExcelFile(res.data, 'vin模板');
            })
            .catch(err => {});
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
    },

    /**
     * 根据数组对象的某个字段去重
     * item.name  是[{name:1}] 根据每条数据的name值来去重
     * */
    unique(arr, val) {
      const res = new Map();
      return arr.filter(item => !res.has(item[val]) && res.set(item[val], 1));
    },

    successHandler(e) {
      console.log('e:::', e);
      if (e != 1) {
        let obj = e[e.length - 1];
        let data = obj['url'];
        // let success = data['success'];
        let successArr = data['success'];

        let newArr = [];
        successArr.forEach((item, index) => {
          item['vinStatus'] = isEmpty(item['vehicleStatus']) ? '' : item['vehicleStatus'];
          item['resDealer'] = isEmpty(item['ownerCode']) ? '' : item['ownerCode'];
          item['salesDealer'] = isEmpty(item['salesCode']) ? '' : item['salesCode'];
          item['name'] = isEmpty(item['customerName']) ? '' : item['customerName'];
          item['productionDate'] = isEmpty(item['productDate']) ? '' : item['productDate'];

          if (this.vinArr.length > 0) {
            this.vinArr.forEach((obj, pos) => {
              if (item['vin'] != obj['vin']) {
                newArr.push(item);
                // this.$refs.table.EXECUTE_INSERT(item);
              }
            });
          } else {
            newArr.push(item);
            // this.$refs.table.EXECUTE_INSERT(item);
          }
        });

        this.$notify.success({ title: '提示信息', message: '您共成功导入' + successArr.length + '条数据' });

        newArr = this.vinArr.concat(newArr);

        let tempArr = this.unique(newArr, 'vin');

        this.dataSource = tempArr;

        this.BaseTable.STOP_LOADING();
      } else {
        this.BaseTable.START_LOADING();
      }
      this.UploadFileIsShow = false;
    },

    /*根据ID查询*/
    async getData() {
      let res = await getByMaId({ maId: this.maId });
      this.fetchParamsVin = Object.assign({}, this.fetchParamsVin, { maId: this.maId, xhrAbort: false });
      if (res.resultCode == 200 && res.success == true) {
        let data = isEmpty(res['data']) ? {} : res['data'];

        let ifPart = isEmpty(data['ifPart']) ? '' : data['ifPart'];
        let ifTech = isEmpty(data['ifTech']) ? '' : data['ifTech'];
        let ifClaim = isEmpty(data['ifClaim']) ? '' : data['ifClaim'];

        let flag = data['ifSettle'] == 10041001 ? 10041001 == ifTech && 10041001 == ifClaim : 10041001 == ifTech;

        if (flag) {
          this.isClicked = true;
        } else {
          this.isClicked = false;
        }
        // let ttRpMaAreas = data['ttRpMaAreas'];
        let ttRpMaLabours = data['ttRpMaLabours'];
        let ttRpMaParts = data['ttRpMaParts'];
        let ttRpMaLogVOS = data['ttRpMaLogVOS'];

        this.BaseTable.EXECUTE_INSERT(ttRpMaAreas);
        // this.BaseSportTable.EXECUTE_INSERT(ttRpMaLabours);
        // this.BasePeijTable.EXECUTE_INSERT(ttRpMaParts);
        // this.BaseSuopeiTable.EXECUTE_INSERT(ttRpMaLogVOS);

        for (let i in data) {
          this.formList.map(x => {
            if (i == x.fieldName) {
              x.initialValue = data[i];
            }
          });
        }
      }
    },

    peijTableChangeFun(val) {
      this.peijArr = val;
    },

    vinTableChangeFun(val) {
      this.vinArr = val;
      console.log('val---', val);
    },

    sportTableChangeFun(val) {
      this.sportArr = val;
      console.log('val---', val);
    },

    async closeMenu(type) {
      if (type == '3') {
        this.$emit('close');
      } else {
        if (type == '1') {
          /*保存数据*/
          this.$refs.formPanel.SUBMIT_FORM();

          let obj = this.saveData;
          console.log('data::', this.data);
          console.log('data::', this.data);
          obj.maId = this.data.maId;
          obj.ttRpMaAreaVOS = this.vinArr;
          obj.ttRpMaLabourVOS = this.sportArr;
          obj.ttRpMaPartVOS = this.peijArr;

          obj.ttRpMaAreaVODel = this.delVinArr;
          obj.ttRpMaLabourVODel = this.delSportArr;
          obj.ttRpMaPartVODel = this.delPartArr;

          let editDate = isEmpty(obj.editDate) ? '0' : obj.editDate;

          let eDate = isEmpty(obj.eDate) ? '0' : obj.eDate;
          let bDate = isEmpty(obj.bDate) ? '0' : obj.bDate;

          // if (moment(eDate) < moment(bDate)) {
          //   this.$notify.warning({ title: '提示信息', message: '活动截止日期不能小于开始日期' });
          //   return;
          // }

          // vin列表为空需要提示
          if (!this.vinArr.length) {
            this.$notify.warning({ title: '提示信息', message: 'VIN列表不能为空！！！' });
            return;
          }

          // if (tempDelearArray.length > 0) {
          //   this.$notify.warning({ title: '提示信息', message: '请将Vin中责任经销商维护完整' });
          //   return;
          // }

          //if (tempArray.length > 0) {
          //  this.$notify.warning({ title: '提示信息', message: '请将配件中数量信息维护完整' });
          //  return;
          //}

          // if (this.handleType == 'add') {
          //   obj.maId = '';
          // }
          let res = await deleteTtRpMaVin(obj);

          if (res.resultCode == 200 && res.success == true) {
            this.$emit('close', 'refresh');
            this.$notify.success({ title: '提示信息', message: '操作成功,如果存在未删除数据说明改vin已经开单' });
          } else {
            // let errMsg = isEmpty(res.errMsg) ? '操作失败' : res.errMsg;
            //
            // this.$notify.error({title: '提示信息', message: errMsg});
          }
        } else if (type == '2') {
          let eDate = this.formList.find(item => item.fieldName == 'eDate').initialValue;
          let bDate = this.formList.find(item => item.fieldName == 'bDate').initialValue;

          if (moment(eDate) < moment(bDate)) {
            this.$notify.warning({ title: '提示信息', message: '活动截止日期不能小于开始日期' });
            return;
          }

          // vin列表为空需要提示
          if (!this.vinArr.length) {
            this.$notify.warning({ title: '提示信息', message: 'VIN列表不能为空！！！' });
            return;
          }

          let curDate = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');

          if (moment(eDate) < moment(curDate)) {
            this.$notify.warning({ title: '提示信息', message: '活动截止日期不能小于当前日期' });
            return;
          }
          //数量不能为空
          let flag = false;
          if (this.peijArr.length) {
            this.peijArr.forEach(x => {
              if (_.isNil(x.counts)) {
                flag = true;
              }
            });
          }
          if (flag) {
            this.$notify.warning({ title: '提示信息', message: '数量不能为空！！！' });
            return;
          }

          let res = await saveDown({ maId: this.maId });

          if (res.resultCode == 200 && res.success == true) {
            this.$emit('close', 'refresh');
            this.$notify.success({ title: '提示信息', message: '操作成功' });
          } else {
            // let errMsg = isEmpty(res.errMsg) ? '操作失败' : res.errMsg;
            //
            // this.$notify.error({title: '提示信息', message: errMsg});
          }
        }
      }
    },
    changeOneAmount(val) {
      if (val == 10041001) {
        this.formList.find(x => x.fieldName == 'oneAmount').disabled = false;
        this.formList.find(x => x.fieldName == 'oneAmount').rules = [{ required: true, trigger: 'change', message: '一口价为是时金额不能为空' }];
      } else {
        this.formList.find(x => x.fieldName == 'oneAmount').disabled = true;
        this.formList.find(x => x.fieldName == 'oneAmount').rules = [];
      }
    },
    closeDialog() {
      console.log('关闭');
      this.visibleVin = false;
      this.visibleSport = false;
      this.visiblePeij = false;
      this.visibleDelear = false;
    },

    /*flag   part:配件删除  area：vin删除  labour ： 项目删除*/
    async delByEdit(flag, id, row) {
      /*本地删除数据*/
      this.BaseTable.EXECUTE_DELETE([row]);
      if (isEmpty(id)) {
        // if (flag == 'area') {
        //   this.BaseTable.EXECUTE_DELETE([row]);
        // } else if (flag == 'labour') {
        //   this.BaseSportTable.EXECUTE_DELETE([row]);
        // } else {
        //   this.BasePeijTable.EXECUTE_DELETE([row]);
        // }
      } else {
        // let res = await delMaItem({'flag': flag, 'id': id, 'maId': this.maId});
        // if (res.resultCode == 200 && res.success == true)
        // {
        //   this.$notify.success({title: '提示信息', message: '操作成功'});
        // if (flag == 'area') {
        //   this.delVinArr.push(id);
        //   this.BaseTable.EXECUTE_DELETE([row]);
        // } else if (flag == 'labour') {
        //   this.delSportArr.push(id);
        //   this.BaseSportTable.EXECUTE_DELETE([row]);
        // } else {
        //   this.delPartArr.push(id);
        //   this.BasePeijTable.EXECUTE_DELETE([row]);
        // }
        // }
      }
    },

    /*vin删除*/
    vinDelFun(row) {
      if (this.handleType == 'edit') {
        this.delByEdit('area', row['areaId'], row);
      } else {
        this.BaseTable.EXECUTE_DELETE([row]);
      }

      // this.$confirm('您确定删除此数据，删除之后不可恢复?', '提示', {
      //   confirmButtonText: '删除',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() =>
      // {
      //
      // }).catch(() =>
      // {
      //
      // });
    },

    /*配件删除*/
    peijDelFun(row) {
      if (this.handleType == 'edit') {
        this.delByEdit('part', row['mpId'], row);
      } else {
        // this.BasePeijTable.EXECUTE_DELETE([row]);
      }
    },
    /*选择经销商*/
    selectDelearFun(arr) {
      if (!isEmpty(this.selectObj)) {
        let index = this.selectObj['$index'];

        let dealerShortname = arr[0].dealerShortname;

        let dealerCode = arr[0].dealerCode;
        let name = arr[0].name;
        let mobile = arr[0].mobile;

        this.vinArr[index].resDealer = dealerCode;

        this.vinArr[index].dealerShortname = dealerShortname;
        this.vinArr[index].name = name;
        this.vinArr[index].mobile = mobile;

        this.BaseTable.DO_REFRESH(false);
      }
    },

    /*配件 */
    selectPeijFun(arr) {
      this.closeDialog();

      if (this.status == 1) {
        /*表单选择*/
        console.log('表单');
        this.formList.find(item => item.fieldName == 'partCode').initialValue = arr[0].partCode;
        this.formList.find(item => item.fieldName == 'partName').initialValue = arr[0].partName;
      } else {
        console.log('新建配件');
      }
      let newArr = [];
      arr.forEach((item, index) => {
        var pos = this.peijArr.findIndex((value, index, arr) => {
          if (value['partCode'] == item['partCode']) {
            /*如果存在则更新数量*/
            if (!isEmpty(item['amount'])) {
              value['amount'] = item['amount'];
            }
            if (!isEmpty(item['counts'])) {
              value['counts'] = item['counts'];
            }
          }
          return value['partCode'] == item['partCode'];
        });
        if (pos == -1) {
          newArr.push(item);
        }
      });

      // this.BasePeijTable.EXECUTE_INSERT(newArr);
      // this.BasePeijTable.DO_REFRESH();
    },

    /*VIN  添加*/
    selectFun(arr) {
      this.closeDialog();

      let newArr = [];
      arr.forEach((item, index) => {
        var pos = this.vinArr.findIndex((value, index, arr) => {
          return value['vin'] == item['vin'];
        });
        if (pos == -1) {
          newArr.push(item);
        }
      });

      this.BaseTable.EXECUTE_INSERT(newArr);
    },

    /*活动删除*/
    sportDelFun(row) {
      if (this.handleType == 'edit') {
        this.delByEdit('labour', row['mlId'], row);
      } else {
        // this.BaseSportTable.EXECUTE_DELETE([row]);
      }
    },
    //=初始化数据
    initData() {
      this.formList.forEach(x => {
        x.initialValue = this.data[x.fieldName];
        x.disabled = true;
      });
    },
    /*添加 活动*/
    selectSportFun(arr) {
      this.closeDialog();

      let newArr = [];
      arr.forEach((item, index) => {
        var pos = this.sportArr.findIndex((value, index, arr) => {
          return value['labourId'] == item['labourId'];
        });
        if (pos == -1) {
          newArr.push(item);
        }
      });
      // this.BaseSportTable.EXECUTE_INSERT(newArr);
    },

    query() {
      this.$refs.formPanel.SUBMIT_FORM();
    },
    reset() {
      this.$refs.formPanel.RESET_FORM();
      this.changeHandle();
    },
    changeHandle(val) {
      this.saveData = val;
    },

    seacherFun() {
      this.status = 1;
      this.visiblePeij = true;
    },
    /*添加配件*/
    addPeij() {
      this.status = 2;
      this.visiblePeij = true;
    },

    /*添加活动*/
    addSport() {
      this.visibleSport = true;
    },

    /*添加vpn*/
    addVpn() {
      this.visibleVin = true;
    },
    /*选择经销商*/
    showDelearFun(row) {
      this.selectObj = row;
      this.visibleDelear = true;
    },

    createFormList() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '批量活动基本信息'
        },

        {
          type: 'INPUT',
          label: '活动编号',
          fieldName: 'maNo',
          itemList: [],
          disabled: true,
          placeholder: '',
          // rules: [{required: true, trigger: 'change'}],
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '活动主题',
          fieldName: 'maTitle',
          disabled: this.handleType == 'edit' ? true : false,
          placeholder: '请输入',
          initialValue: ''
        },
        {
          type: 'INPUT_NUMBER',
          label: '批量活动完成率',
          fieldName: 'overRate',
          placeholder: '',
          max: 100,
          // disabled: this.handleType == 'edit' ? true : false,
          initialValue: ''
        },
        {
          type: 'DATE',
          label: '活动开始日期',
          fieldName: 'bDate',
          format: 'yyyy-MM-dd',
          disabled: this.handleType == 'edit' ? false : false,
          placeholder: '请选择',
          initialValue: ''
        },

        {
          type: 'DATE',
          label: '活动截止日期',
          fieldName: 'eDate',
          format: 'yyyy-MM-dd',
          disabled: this.handleType == 'edit' ? false : false,
          placeholder: '请选择',
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '是否OTA活动',
          fieldName: 'ifOta',
          placeholder: '',
          initialValue: '',
          hidden: getAppId().toLowerCase() == 'arcfox' ? true : false,
          disabled: this.handleType == 'edit' ? false : false,
          itemList: this.createDictList(1004)
        },
        {
          type: 'INPUT',
          label: '主损件代码',
          fieldName: 'partCode',
          placeholder: '请选择',
          readonly: true,
          initialValue: '',
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.seacherFun()}></el-button>
              </div>
            );
          }
        },
        {
          type: 'INPUT',
          label: '主损件名称',
          fieldName: 'partName',
          placeholder: '请选择',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '供应商代码',
          fieldName: 'supCode',
          placeholder: '请选择',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '供应商',
          fieldName: 'supName',
          placeholder: '请选择',
          readonly: true,
          disabled: true
        },
        {
          type: 'INPUT',
          label: '故障现象代码',
          fieldName: 'faultCode',
          readonly: true,
          disabled: true
        },
        {
          type: 'INPUT',
          label: '故障现象描述',
          fieldName: 'faultName',
          placeholder: '请输入...',
          initialValue: undefined,
          disabled: true
        },
        {
          type: 'INPUT',
          label: '一级代码',
          fieldName: 'sysCode1',
          placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '一级名称',
          fieldName: 'sysName1',
          placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '二级代码',
          fieldName: 'sysCode2',
          placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '二级名称',
          fieldName: 'sysName2',
          placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '三级代码',
          fieldName: 'sysCode3',
          placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '三级名称',
          fieldName: 'sysName3',
          placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '故障代码',
          fieldName: 'sysCode4',
          placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '故障描述',
          fieldName: 'sysName4',
          placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '分类',
          fieldName: 'frCode',
          readonly: true,
          disabled: true
        },
        {
          type: 'INPUT',
          label: '故障原因描述',
          fieldName: 'frName',
          placeholder: '请输入故障原因描述...',
          initialValue: undefined,
          disabled: true
        },
        {
          type: 'SELECT',
          label: '活动等级',
          fieldName: 'maLevel',
          placeholder: '',
          initialValue: '',
          disabled: this.handleType == 'edit' ? false : false,
          itemList: this.createDictList(1017)
        },
        {
          type: 'INPUT',
          label: '活动策略',
          fieldName: 'maStrategy',
          placeholder: '请选择',
          disabled: this.handleType == 'edit' ? true : false,
          initialValue: ''
        },
        {
          type: 'INPUT_NUMBER',
          label: '预算编号',
          fieldName: 'budgetNo',
          placeholder: '请选择',
          disabled: this.handleType == 'edit' ? true : false,
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '是否索赔结算',
          fieldName: 'ifSettle',
          placeholder: '请选择',
          disabled: this.handleType == 'edit' ? false : false,
          itemList: this.createDictList(1004),
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '是否一口价',
          fieldName: 'isOne',
          placeholder: '请选择',
          disabled: this.handleType == 'edit' ? false : false,
          itemList: this.createDictList(1004),
          change: this.changeOneAmount,
          initialValue: ''
        },
        {
          type: 'INPUT_NUMBER',
          label: '一口价金额',
          fieldName: 'oneAmount',
          placeholder: '请选择',
          rules: [],
          disabled: false,
          initialValue: ''
        },
        {
          type: 'TEXT_AREA',
          label: '活动说明',
          fieldName: 'maRemarks',
          placeholder: '请选择',
          disabled: this.handleType == 'edit' ? false : false,
          initialValue: '',
          selfCols: 3
        },
        {
          type: 'SELECT',
          label: '配件满足情况',
          fieldName: 'ifPart',
          placeholder: '',
          hidden: this.handleType == 'edit' ? false : true,
          initialValue: '',
          itemList: this.createDictList(1004)
        },
        {
          type: 'INPUT',
          label: '配件满足百分比',
          fieldName: 'percent',
          placeholder: '',
          numberFormat: true,
          hidden: this.handleType == 'edit' ? false : true,
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '技术文件情况',
          disabled: false,
          fieldName: 'ifTech',
          placeholder: '',
          hidden: this.handleType == 'edit' ? false : true,
          initialValue: '',
          itemList: this.createDictList(1004)
        },
        {
          type: 'SELECT',
          label: '活动状态',
          disabled: true,
          fieldName: 'maStatus',
          placeholder: '',
          hidden: this.handleType == 'edit' ? false : true,
          initialValue: '',
          itemList: this.createDictList(1014)
        },
        {
          type: 'INPUT_NUMBER',
          label: '经销商修改销售状态时效(天)',
          disabled: false,
          fieldName: 'editDate',
          labelWidth: '180px',
          placeholder: '',
          hidden: this.handleType == 'edit' ? false : true,
          initialValue: ''
        },
        {
          type: 'DATE',
          label: '考核截止日期',
          fieldName: 'verifyDate',
          format: 'yyyy-MM-dd',
          placeholder: '请选择',
          hidden: this.handleType == 'edit' ? false : true,
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '是否返件',
          fieldName: 'isReturn',
          placeholder: '请选择',
          disabled: true,
          // rules: [{ required: true, message: '请选择', trigger: 'change' }],
          itemList: this.createDictList(1004),
          initialValue: '',
          disabled: true
        }
      ];
    },

    /*索赔*/
    createTableColumnSuopei() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作人',
          dataIndex: 'createdBy',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [],
          dictItems: []
        },
        {
          title: '操作时间',
          dataIndex: 'createdAt',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '操作后状态',
          dataIndex: 'checkStatus',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList(1022),
          render: props => {
            console.log(props.row.checkStatus);
            return <span>{this.createDictText(props.row.checkStatus, 1022)}</span>;
          }
        },
        {
          title: '审核说明',
          dataIndex: 'checkRemarks',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },

    /*配件*/
    createTableColumnPeij() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" disabled={this.disableState} onClick={() => this.peijDelFun(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '配件代码',
          dataIndex: 'partCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'partName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '单位',
          dataIndex: 'unit',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [],
          dictItems: []
        },
        {
          title: '数量',
          dataIndex: 'counts',
          sorter: true,
          filter: true,
          filterType: 'input',
          editType: 'number',
          editRequired: true,
          // editPattern:/^[1][3,4,5,7,8][0-9]{9}$/,
          editable: true
        },
        {
          title: '索赔单价',
          dataIndex: 'price',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2
        },
        {
          title: '配件渠道',
          dataIndex: 'partFrom',
          sorter: true,
          editType: 'select',
          editItems: this.createDictList('1025'),
          // this.createDictList('1025')
          editRequired: true,
          // editPattern:/^[1][3,4,5,7,8][0-9]{9}$/,
          editable: true
        },
        {
          title: '索赔总价',
          dataIndex: 'amount',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2
        }
      ];
    },

    /*活动*/
    createTableColumnSport() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" disabled={this.disableState} onClick={() => this.sportDelFun(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '活动项目代码',
          dataIndex: 'labourCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '活动项目名称',
          dataIndex: 'labourName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '标准工时',
          dataIndex: 'stdLabourHour',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.vinDelFun(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: 'VIN',
          dataIndex: 'vin',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车辆状态',
          dataIndex: 'vinStatus',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList(6040),
          render: props => {
            return <span>{this.createDictText(props.row.vinStatus, 6040)}</span>;
          }
        },
        {
          title: '责任经销商',
          dataIndex: 'resDealer',
          sorter: true,
          filter: true,
          dictItems: [],
          filterItems: [],
          filterType: 'checkbox',
          render: props => {
            return (
              <div style="width: 100px">
                <el-button size="mini" type="text" disabled={this.disableState} icon="el-icon-search" onClick={() => this.showDelearFun(props.row)}>
                  {this.createDealerText(props.row.resDealer)}
                </el-button>
              </div>
            );
          }
        },
        {
          title: '车型名称',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户名称',
          dataIndex: 'name',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户电话',
          dataIndex: 'mobile',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '生产日期',
          dataIndex: 'productionDate',
          sorter: true,
          dateFormat: 'yyyy-MM-dd',
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '销售日期',
          dataIndex: 'salesDate',
          sorter: true,
          dateFormat: 'yyyy-MM-dd',
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '销售经销商',
          dataIndex: 'salesDealer',
          sorter: true,
          filter: true,
          filterItems: [],
          filterType: 'checkbox',
          dictItems: []
        }
      ];
    }
  }
};
</script>

<style scoped lang="less">
.bg1 {
  border: 1px solid @borderColor;
  border-radius: @borderRadius;
  box-shadow: @boxShadow;
  padding: @modulePadding;
  padding-left: 0;
  padding-top: 15px;
  padding-bottom: 15px;
}

.bg2 {
  margin-top: 10px;
  margin-bottom: 10px;
}

.btn {
  text-align: center;
}

.btnStyle {
  margin-top: 10px;
}
</style>
